package com.cavy.platform.server.validator;

import com.cavy.platform.server.dto.AbstractConfigMapCreateDto;
import com.cavy.platform.server.repository.ConfigMapRepository;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class ConfigMapNotRepeatValidator implements ConstraintValidator<ConfigMapNotRepeat, AbstractConfigMapCreateDto> {

    @Autowired
    private ConfigMapRepository repository;

    @Override
    public void initialize(ConfigMapNotRepeat configMapNotRepeat) {
    }

    @Override
    public boolean isValid(AbstractConfigMapCreateDto dto,
                           ConstraintValidatorContext context) {
        int count = repository.countByWorkspaceAndName(dto.getWorkspace(), dto.getName());
        if (count > 0) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
                    .addPropertyNode(dto.getNameField()).addConstraintViolation();
            return false;
        }
        return true;
    }
}
